package com.lql.parseArray;

import java.io.*;
import java.util.Arrays;

/**
 * 稀疏矩阵
 */
public class parseArrays {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        System.out.println("#####################原始矩阵转稀疏矩阵##################");
        // 定义元素原始数组
        int[][] chessArrays = new int[11][11];
        chessArrays[1][2] = 1;
        chessArrays[2][3] = 3;
        chessArrays[3][3] = 4;
        System.out.println("原始矩阵：");
        Arrays.stream(chessArrays).forEach(row -> {
            Arrays.stream(row).forEach(cloumn -> {
                System.out.print("\t" + cloumn);
            });
            System.out.println();
        });
        // 求出矩阵中不为零的个数
        int sum = 0;
        for (int[] rows : chessArrays) {
            for (int row : rows) {
                if (row != 0) {
                    sum++;
                }
            }
        }
        // 定义稀疏矩阵
        int[][] sparseArrays = new int[sum + 1][3];
        sparseArrays[0][0] = 11;
        sparseArrays[0][1] = 11;
        sparseArrays[0][2] = sum;
        // 定义计数器
        int count = 0;
        for (int row = 0; row < chessArrays.length; row++) {
            for (int cloum = 0; cloum < chessArrays[row].length; cloum++) {
                if (chessArrays[row][cloum] != 0) {
                    count++;
                    sparseArrays[count][0] = row;
                    sparseArrays[count][1] = cloum;
                    sparseArrays[count][2] = chessArrays[row][cloum];

                }
            }
        }
        System.out.println("稀疏矩阵：");
        Arrays.stream(sparseArrays).forEach(row -> {
            Arrays.stream(row).forEach(cloumn -> {
                System.out.print("\t" + cloumn);
            });
            System.out.println();
        });
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("data.data"));
        objectOutputStream.writeObject(sparseArrays);

        System.out.println("#####################稀疏矩阵转为原始矩阵##################");
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("data.data"));
        int[][] sparseArrays1 = (int[][])objectInputStream.readObject();
        int[][] chessArrays1 = new int[sparseArrays1[0][0]][sparseArrays1[0][1]];
        for (int row = 1; row < sparseArrays1.length; row++) {
                chessArrays1[sparseArrays1[row][0]][sparseArrays1[row][1]] = sparseArrays1[row][2];
        }
        System.out.println("恢复后的原始矩阵：");
        Arrays.stream(chessArrays1).forEach(row -> {
            Arrays.stream(row).forEach(cloumn -> {
                System.out.print("\t" + cloumn);
            });
            System.out.println();
        });

    }
}
